package com.liu.manag.utils;

import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

public class CSVUtil {

    //csv 文件列分隔符
    private static final String CSV_COLUMN_SEPAPATOR = ",";

    private static final String CSV_ROW_SEPAPATOR = System.lineSeparator();

    public static void responseSetProperties(String fileName,
                                             HttpServletResponse response) throws UnsupportedEncodingException {
        //文件名
        String fn  =fileName + ".csv";
        String charset = "UTF-8";

        //设置浏览器保存响应并发起下载
        response.setContentType("application/ms-txt.numberformat:@");
        response.setCharacterEncoding(charset);
        response.setHeader("Pragm","pulbic");
        response.setHeader("Cache-Control","max-age=30");
        response.setHeader("Content-Disposition","attachment: filename="+ URLEncoder.encode(fn,charset));

    }

    public static void doExport(List<Map<String, Object>> dataList, String colNames, String mapKey, OutputStream outputStream) throws IOException {
        StringBuffer buffer = new StringBuffer();
        String[] colNameArray = colNames.split(",");
        String[] mapKeyArray  = mapKey.split(",");

        //组装表头
        for(String colName: colNameArray){
            buffer.append(colName).append(CSV_COLUMN_SEPAPATOR);
        }

        buffer.append(CSV_ROW_SEPAPATOR);

        //组装数据
        if(!CollectionUtils.isEmpty(dataList)){
            for (Map<String, Object> data : dataList){
                for(String key : mapKeyArray){
                    buffer.append(data.get(key)).append(CSV_COLUMN_SEPAPATOR);
                }
                buffer.append(CSV_ROW_SEPAPATOR);
            }
        }

        outputStream.write(buffer.toString().getBytes("UTF-8"));
        outputStream.flush();

    }




}
